package com.nys.cqhttp.message.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.nys.cqhttp.mapper.TheMessageMapper;
import com.nys.cqhttp.message.factory.IMessageHandler;
import com.nys.cqhttp.model.Massage;
import com.nys.cqhttp.model.TheMessage;
import com.nys.cqhttp.model.TheMessageExample;
import com.nys.cqhttp.param.Context;
import com.nys.cqhttp.param.MessageParam;
import com.nys.cqhttp.util.Chinese2Number;
import com.nys.cqhttp.util.NumberToCnUtil;
import com.nys.cqhttp.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * DirectUrlMessageHandler
 *
 * @author nysheng
 * @version 1.0.0
 * @description 服务器
 * @date 2021/12/28 19:53
 */
@Slf4j
@Component
public class CFWQMessageHandler implements IMessageHandler {
  @Autowired private TheMessageMapper theMessageMapper;
  private static CFWQMessageHandler cfwqMessageHandler;

  @PostConstruct
  public void init() throws Exception {
    cfwqMessageHandler = this;
    theMessageMapper = this.theMessageMapper;
  }

  @Override
  public List<String> listHandler(Massage message, Context context) {
    return Arrays.asList(handler(message, context));
  }

  @Override
  public String handler(Massage messagePojo, Context context) {
    RestTemplate restTemplate = SpringContextUtil.getBean("restTemplate");
    try {
      MessageParam messageParam = context.getMessageParam();
      String[] arr = {"1", "2", "3", "4", "5", "6"};
      if (messageParam.getMessage().contains(".-")) {
        TheMessageExample theMessageExample = new TheMessageExample();
        TheMessageExample.Criteria criteria = theMessageExample.createCriteria();
        criteria.andMessageLike("CF-%");
        criteria.andUserQqEqualTo(messageParam.getSenderId());
        criteria.andJqrQqEqualTo(messageParam.getSelfId());
        List<TheMessage> theMessages =
            cfwqMessageHandler.theMessageMapper.selectByExample(theMessageExample);
        String[] split = messageParam.getMessage().split(".-");
        if (ArrayUtils.contains(arr, split[0])) {
          if (CollectionUtils.isNotEmpty(theMessages)) {
            TheMessage theMessage = theMessages.get(0);
            String res = theMessage.getRes();
            List<JSONObject> list = JSONObject.parseObject(res, List.class);
            Integer i = Integer.valueOf(split[0])-1;
            if (list.size() >= i) {
              JSONObject jsonObject = list.get(i);
              String body =
                  restTemplate
                      .postForEntity(
                          "https://api.dstserverlist.top/api/details/"
                              + jsonObject.getString("RowId"),
                          null,
                          String.class)
                      .getBody();
              JSONObject jsonObject1 = JSONObject.parseObject(body);
              JSONObject daysInfo = jsonObject1.getObject("DaysInfo", JSONObject.class);
              List<JSONObject> players = jsonObject1.getObject("Players", List.class);
              String play = "";
              for (int i1 = 0; i1 < players.size(); i1++) {
                JSONObject player = players.get(i1);
                play += player.getString("Name") + "(" + player.getString("Prefab") + ") ";

              }

              return jsonObject1.getString("Name")
                  + "("
                  + jsonObject1.getString("Connected")
                  + "/"
                  + jsonObject1.getString("MaxConnections")
                  + ")\n平台:" + list.get(i).getString("Platform")+
                      "\n模式:"
                  + jsonObject1.getString("Mode")
                  + "/"
                  + jsonObject1.getString("Intent")
                  + "\n天数信息:第"
                  + daysInfo.getString("Day")
                  + "天 "
                  + jsonObject1.getString("Season")
                  + " ("
                  + daysInfo.getString("DaysElapsedInSeason")
                  + "/"
                  + (daysInfo.getInteger("DaysElapsedInSeason")
                      + daysInfo.getInteger("DaysLeftInSeason"))
                  + ")\n描述:"
                  + jsonObject1.getString("Desc")
                  + "\n玩家:"
                  + play;
            }
          }
        } else {
          if (CollectionUtils.isNotEmpty(theMessages)) {
            TheMessage theMessage = theMessages.get(0);
            String[] split1 = theMessage.getMessage().split("-");
            Integer convert = Chinese2Number.convert(split[0])-1;
            String url =
                String.format(
                    "https://api.dstserverlist.top/api/list?name=%s&pageCount=6&page="+convert,
                    split1[1]);
            String body = restTemplate.postForEntity(url, null, String.class).getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            String res =
                "当前是第"
                    + NumberToCnUtil.toChineseLower((jsonObject.getInteger("Page") + 1))
                    + "页   一共"
                    + NumberToCnUtil.toChineseLower((jsonObject.getInteger("MaxPage") + 1))
                    + "页   "
                    + jsonObject.get("AllCount")
                    + "条";
            List<JSONObject> list = jsonObject.getObject("List", List.class);
            for (int i = 0; i < list.size(); i++) {
              res +=
                  "\n"
                      + (i + 1)
                      + "."
                      + list.get(i).getString("Name")
                      + "("
                      + list.get(i).getString("Connected")
                      + "/"
                      + list.get(i).getString("MaxConnections")
                      + ")" + list.get(i).getString("Platform");
            }

            theMessage.setRes(JSONObject.toJSONString(list));
            cfwqMessageHandler.theMessageMapper.updateByPrimaryKeySelective(theMessage);
            return res;
          }
        }
      } else if (messageParam.getMessage().contains("CF-")){
        String[] split = messageParam.getMessage().split("-");
        String url = String.format(messagePojo.getValue(), split[1]);
        String body = restTemplate.postForEntity(url, null, String.class).getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        String res =
            "当前是第"
                + NumberToCnUtil.toChineseLower((jsonObject.getInteger("Page") + 1))
                + "页   一共"
                + NumberToCnUtil.toChineseLower((jsonObject.getInteger("MaxPage") + 1))
                + "页   "
                + jsonObject.get("AllCount")
                + "条";
        List<JSONObject> list = jsonObject.getObject("List", List.class);
        for (int i = 0; i < list.size(); i++) {
          res +=
              "\n"
                  + (i + 1)
                  + "."
                  + list.get(i).getString("Name")
                  + "("
                  + list.get(i).getString("Connected")
                  + "/"
                  + list.get(i).getString("MaxConnections")
                  + ")"+ list.get(i).getString("Platform");
        }
        TheMessageExample theMessageExample = new TheMessageExample();
        TheMessageExample.Criteria criteria = theMessageExample.createCriteria();
        criteria.andMessageLike("CF-%");
        criteria.andUserQqEqualTo(messageParam.getSenderId());
        criteria.andJqrQqEqualTo(messageParam.getSelfId());
        List<TheMessage> theMessages =
                cfwqMessageHandler.theMessageMapper.selectByExample(theMessageExample);
        if(CollectionUtils.isNotEmpty(theMessages)){
          TheMessage theMessage = theMessages.get(0);
          theMessage.setMessage(messageParam.getMessage());
          theMessage.setRes(JSONObject.toJSONString(list));
          cfwqMessageHandler.theMessageMapper.updateByPrimaryKeySelective(theMessage);
        } else {
          TheMessage theMessage = new TheMessage();
          theMessage.setMessage(messageParam.getMessage());
          theMessage.setJqrQq(messageParam.getSelfId());
          theMessage.setUserQq(messageParam.getSenderId());
          theMessage.setRes(JSONObject.toJSONString(list));
          cfwqMessageHandler.theMessageMapper.insertSelective(theMessage);
        }
        return res;
      }
      return null;
    } catch (Exception e) {
      log.info(e.toString());
      return "查询失败";
    }
  }
}
